package com.shqcjd.yunweiyanoperator.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.MajorBean;
import com.shqcjd.yunweiyanoperator.model.pojo.SquareListBean;
import com.shqcjd.yunweiyanoperator.model.pojo.SquareRequest;
import com.shqcjd.yunweiyanoperator.model.pojo.VideoCategory;
import com.shqcjd.yunweiyanoperator.ui.activity.VideoDetailsActivity;
import com.shqcjd.yunweiyanoperator.ui.adapter.SquareVideoListAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseFragment;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.Config;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.SpacesItemDecoration;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.disposables.Disposable;

public class SquareFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rv_video_list)
    RecyclerView rvVideoList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.filter_btn)
    TextView filterBtn;
    @BindView(R.id.rl_pop)
    RelativeLayout rlPop;

    private int mNextRequestPage = 1;
    private static final int PAGE_SIZE = Config.PAGE_TOTAL;
    private SquareVideoListAdapter squareVideoListAdapter;
    private View notDataView;
    private String keyword = "";
    private String videoCategoryId = "0";
    private int userId;
    private View contentView;

    private ArrayList<String> mTypeVals = new ArrayList<>();
    private ArrayList<String> majorIVals = new ArrayList<>();
    private ArrayList<Integer> majorIId = new ArrayList<>();
    private ArrayList<String> mTypeId = new ArrayList<>();
    private RelativeLayout rl;
    private LinearLayout ll_pop_content;
    private TagFlowLayout flowlayout;
    private Button btn_pop_commit;
    private Button btn_pop_reset;
    private TagFlowLayout flowlayout_specialty;
    private List<Integer> majorIds;

    public static SquareFragment newInstance() {
        return new SquareFragment();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_square_layout;
    }

    @Override
    public void init() {
    }

    @Override
    public void initView(View rootView) {
        userId = PrefUtils.getInt(getContext(), PrefUtils.USER_ID, -1);
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvVideoList.getParent(), false);
        initRefreshLayout();
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rvVideoList.setLayoutManager(staggeredGridLayoutManager);
        squareVideoListAdapter = new SquareVideoListAdapter();
        squareVideoListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SquareListBean.ListBean item = (SquareListBean.ListBean) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.fl_sc://收藏
                        if (!item.collected) {
                            setCollection(item, position);
                        } else {
                            ToastUtils.showShort(getContext(), "您已经收藏过");
                        }
                        break;
                    case R.id.fl_like://点赞
                        if (!item.liked) {
                            setLike(item, position);
                        } else {
                            ToastUtils.showShort(getContext(), "您已经点赞过");
                        }
                        break;
                    case R.id.btn_details://详情
                        Intent intent = new Intent(getContext(), VideoDetailsActivity.class);
                        intent.putExtra("title", item.title);
                        intent.putExtra("url", item.videoUrl);
                        intent.putExtra("imageUrl", item.imageUrl);
                        intent.putExtra("videoCategoryName", item.videoCategoryName);
                        intent.putExtra("userName", item.userName);
                        intent.putExtra("callRecord",item.callRecord);
                        startActivity(intent);
                        break;
                }
            }
        });
        rvVideoList.setAdapter(squareVideoListAdapter);
        rvVideoList.addItemDecoration(new SpacesItemDecoration(16, 16));
        squareVideoListAdapter.setOnLoadMoreListener(this, rvVideoList);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                keyword = editable.toString();
                refresh();
            }
        });


    }

    private void setLike(SquareListBean.ListBean item, int position) {
        Map<String, Integer> map = new HashMap<>();
        map.put("shareId", item.id);
        map.put("userId", userId);
        ApiService.setLike(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                            item.likeNum++;
                            item.liked = true;
                            squareVideoListAdapter.refreshNotifyItemChanged(position);
                            ToastUtils.showShort(getContext(), "点赞成功");
                        } else {
                            ToastUtils.showShort(getContext(), responseData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(getContext(), "点赞失败");
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void setCollection(SquareListBean.ListBean item, int position) {

        Map<String, Integer> map = new HashMap<>();
        map.put("shareId", item.id);
        map.put("userId", userId);
        ApiService.createCollection(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                            item.collectNum++;
                            item.collected = true;
                            squareVideoListAdapter.refreshNotifyItemChanged(position);
                            ToastUtils.showShort(getContext(), "收藏成功");
                        } else {
                            ToastUtils.showShort(getContext(), responseData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(getContext(), "收藏失败");
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    public void initData() {
        refresh();
    }

    private void initRefreshLayout() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        swipeLayout.setRefreshing(true);
    }

    private void refresh() {
        GSYVideoManager.releaseAllVideos();
        mNextRequestPage = 1;
        squareVideoListAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        SquareRequest request = new SquareRequest();
        request.keyword=keyword;
        request.page = mNextRequestPage;
        request.size = PAGE_SIZE;
        request.videoCategoryId = videoCategoryId;
        request.majorIds = majorIds;
        ApiService.getSquareList(new Gson().toJson(request))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<SquareListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        swipeLayout.setRefreshing(true);
                    }

                    @Override
                    public void _onNext(ResponseData<SquareListBean> retData) {
                        if (retData.retCode == 10000) {
                            setData(true, retData.data.list);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(getContext(), errorMessage);
                        squareVideoListAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        squareVideoListAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }
                });

    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void loadMore() {
        GSYVideoManager.releaseAllVideos();
        SquareRequest request = new SquareRequest();
        request.keyword=keyword;
        request.page = mNextRequestPage;
        request.size = PAGE_SIZE;
        request.videoCategoryId = videoCategoryId;
        request.majorIds = majorIds;
        ApiService.getSquareList(new Gson().toJson(request))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<SquareListBean>>() {
                    @Override
                    public void _onNext(ResponseData<SquareListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh = mNextRequestPage == 1;
                            setData(isRefresh, retData.data.list);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(getContext(), errorMessage);
                        squareVideoListAdapter.loadMoreFail();
                    }

                });
    }

    private void setData(boolean isRefresh, List data) {

        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                squareVideoListAdapter.setNewData(data);
            } else {
                squareVideoListAdapter.setNewData(null);
                squareVideoListAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                squareVideoListAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            squareVideoListAdapter.loadMoreEnd(isRefresh);
        } else {
            squareVideoListAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onVisible() {
//        GSYVideoManager.onResume(false);
    }

    @Override
    public void onInvisible() {
        //
        GSYVideoManager.onPause();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
//        GSYVideoManager.onResume(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .navigationBarColor(R.color.bgcolor)
                .init();
    }


    @OnClick(R.id.filter_btn)
    public void onViewClicked() {
        //筛选
        showPopupWindow(rlPop);
    }

    private void showPopupWindow(ViewGroup view) {
        if (contentView != null) {
            contentView.setVisibility(View.VISIBLE);
            refreshTypeData(flowlayout);
            getMajorData(flowlayout_specialty);
            return;
        } else {
            contentView = LayoutInflater.from(view.getContext()).inflate(
                    R.layout.pop_window, view, false);
            view.addView(contentView);

            rl = contentView.findViewById(R.id.rl);
            ll_pop_content = contentView.findViewById(R.id.ll_pop_content);
            flowlayout = contentView.findViewById(R.id.id_flowlayout);
            btn_pop_commit = contentView.findViewById(R.id.btn_pop_commit);
            btn_pop_reset = contentView.findViewById(R.id.btn_pop_reset);
            flowlayout_specialty = contentView.findViewById(R.id.flowlayout_specialty);
            refreshTypeData(flowlayout);
            getMajorData(flowlayout_specialty);
        }


        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentView.setVisibility(View.GONE);
            }
        });
        ll_pop_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        btn_pop_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Set<Integer> selectedList = flowlayout.getSelectedList();
                List<String> typeList = new ArrayList<>();
                for (Integer integer : selectedList) {
                    typeList.add(mTypeId.get(integer));
                }
                String content = typeList.toString().replace("[", "").replace("]", "");
                videoCategoryId = content.isEmpty() ? "0" : content;//0 表示全部
                contentView.setVisibility(View.GONE);


                Set<Integer> majorList = flowlayout_specialty.getSelectedList();
                List<Integer> ids = new ArrayList<>();
                for (Integer integer : majorList) {
                    ids.add(majorIId.get(integer));
                }
                majorIds = ids;

                refresh();
            }
        });


    }

    private void refreshTypeData(TagFlowLayout flowlayout) {
        ApiService.getVideoCategory()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<VideoCategory>>>() {
                    @Override
                    public void _onNext(ResponseData<List<VideoCategory>> retData) {
                        if (retData.retCode == 10000) {
                            mTypeVals.clear();
                            mTypeId.clear();
                            for (VideoCategory category : retData.data) {
                                mTypeVals.add(category.name);
                                mTypeId.add(category.id);
                            }
                            TagAdapter tagAdapter = new TagAdapter<String>(mTypeVals.toArray(new String[mTypeVals.size()])) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.tv_tag,
                                            flowlayout, false);
                                    tv.setText(s);
                                    return tv;
                                }

                            };
                            flowlayout.setAdapter(tagAdapter);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {

                    }
                });
    }

    private void getMajorData(TagFlowLayout view){
        ApiService.getMajor()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<MajorBean>>>() {
                    @Override
                    public void _onNext(ResponseData<List<MajorBean>> retData) {
                        if (retData.retCode == 10000) {
                            majorIVals.clear();
                            majorIId.clear();
                            for (MajorBean majorBean : retData.data) {
                                majorIVals.add(majorBean.name);
                                majorIId.add(majorBean.id);
                            }

                            TagAdapter tagAdapter = new TagAdapter<String>(majorIVals.toArray(new String[majorIVals.size()])) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.tv_tag,
                                            view, false);
                                    tv.setText(s);
                                    return tv;
                                }

                            };
                            view.setAdapter(tagAdapter);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {

                    }
                });
    }
}
